package com.asia5b.a5mall.middleware.logic.viewmodel.member

import androidx.lifecycle.MutableLiveData
import com.asia5b.a5mall.middleware.base.SimpleViewModel
import com.asia5b.a5mall.middleware.model.bean.PostCommentBean
import com.asia5b.a5mall.middleware.model.shop.AbsShopModel
import io.reactivex.Observable
import io.reactivex.functions.Consumer
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File

/**
 * Created by zhangyuncai on 2019/12/21.
 * @Note   发送评论逻辑控制器
 */
class PostCommentActivityVM :SimpleViewModel() {


    fun commit(data: PostCommentBean) {
        val uploadImgList = arrayListOf<String>()
        for (postGoodsModel in data.comments) {
            uploadImgList.addAll(postGoodsModel.waitUploadImages)
        }
        val observable = Observable.fromIterable(uploadImgList)
                .flatMap { waitUploadImageFilePath ->
                    uploader(waitUploadImageFilePath)
                            .map { uploadImageResultPath ->
                                /*
                                把本地图片替换成网络图片
                                 */
                                for (postGoodsModel in data.comments) {
                                    if (postGoodsModel.waitUploadImages.contains(waitUploadImageFilePath)) {
                                        postGoodsModel.images.add(uploadImageResultPath)
                                        postGoodsModel.waitUploadImages.remove(waitUploadImageFilePath)
                                    }
                                }
                                uploadImageResultPath
                            }
                }
                .toList()
                .flatMapObservable {
                    memberApi.addComment(data)
                }

        baseSubscribe(observable, Consumer {
//            providerView().commitResult()
            commitResultLiveData.value=true
        })

    }

    val commitResultLiveData=MutableLiveData<Boolean>()

    val getShopResultLiveData=MutableLiveData<AbsShopModel>()
    fun getShop(shopId: Int) {
        val observable = shopApi.getShop(shopId)
        baseSubscribe(observable, Consumer {
//            providerView().getShopResult(it!!)
            getShopResultLiveData.value=it
        })
    }

    /**
     * 将图片资料上传至云服务器
     */
    fun uploader(filePath: String): Observable<String> {
        val localFile = File(filePath)
        val localRequestBody = RequestBody.create("image/jpeg".toMediaTypeOrNull(), localFile)
        val localPart = MultipartBody.Part.createFormData("file", localFile.name, localRequestBody)
        return baseApi.uploader(localPart, "")
                .map { uploadImgResModel ->
                    return@map uploadImgResModel.url
                }
    }
}